import logging
from pyramid.view import view_config
from bbkb import stats
from bbkb.KnowledgeBase import KnowledgeBase as kb
from bbkb.KBQuery import query_knowledgebase

log = logging.getLogger(__name__)

@view_config(route_name='index_view', renderer='bbkb:templates/main.pt')
def index_view(request):
    """Default index handler"""
    return {
        'num_kb_entries':len(kb.kb),
        'lookup_table_names':sorted(kb.lookup_tables),
    }

@view_config(route_name='legacy_view', renderer='bbkb:templates/legacy.pt')
def legacy_view(request):
    """Legacy (v1.0) view handler"""
    return {'project':'bbkb'}
    
@view_config(route_name='query_view', renderer='json')
def query(request):
    """Handles sentence based queries to the knowledgebase"""
    log.debug("Query requested for: %s", request.params['object'])
    sentence = request.params['object']
    results = query_knowledgebase(sentence)
    return {'data':results}
    
@view_config(route_name='reconstitute_view', renderer='json')
def reconstitute(request):
    """Loads data for requested lookup table"""
    log.debug("Reconstitute requested for: %s", request.params['object'])
    requested_object = request.params['object']
    object_data = kb.get(requested_object)
    data = []
    for id in object_data:
        data.append({'id':id,'value':object_data[id]})
    print data
    return {'data':data}

@view_config(route_name='fact_frequency_view', renderer='json')
def fact_frequency(request):
    """Loads frequency of fact entries from kb"""
    freqs = stats.calculate_fact_frequency()
    data = []
    for value,frequency in freqs:
        data.append({'id':'', 'value':value, 'frequency':frequency})
    return {'data':data}